package Code.controller;

import Code.model.GUI;
import Code.model.ManagerAppTools;
import Code.model.Manager;
import Code.model.FileListCell;
import Code.model.ItemData;
import Code.model.DirTreeCell;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.net.URL;
import java.util.ResourceBundle;


public class ManagerController implements Initializable {

    private static Stage stage = null;

    public static Stage getStage() {
        return stage;
    }

    public static void setStage(Stage stage) {
        ManagerController.stage = stage;
    }
    @FXML
    private TextField commandText;

    /*********
     * 目录树 *
     *********/

    private TreeItem<ItemData> curItem; //当前目录

    @FXML
    private AnchorPane limitPane;

    @FXML
    private PieChart pieChart;

    @FXML
    private Button About;
    @FXML
    private Button help;
    @FXML
    void aboutAction(ActionEvent event) {
        Stage stage1 = new Stage();
        stage1.setTitle("作者信息");
        Label label1 = new Label("陈钦健 202125220401");
        Label label2 = new Label("庄奕锋 202125220330");
        Label label3 = new Label("陈逸润 202125220403");
        label1.setStyle("-fx-font-family: 'Microsoft YaHe';-fx-font-size: 24;");
        label2.setStyle("-fx-font-family: 'Microsoft YaHe';-fx-font-size: 24;");
        label3.setStyle("-fx-font-family: 'Microsoft YaHe';-fx-font-size: 24;");

        VBox vbox = new VBox(10);
        vbox.getChildren().addAll(label1, label2, label3);
        Scene scene = new Scene(vbox, 300, 200);
        stage1.setScene(scene);
        Image image = new Image("/resource/Image/about.png");
        stage1.getIcons().add(image);
        stage1.show();
    }
    @FXML
    void helpAction(ActionEvent event) {
        Stage stage2 = new Stage();
        stage2.setTitle("帮助");
        Label label1 = new Label("创造指令：create  删除指令：delete ");
        label1.setStyle("-fx-font-family: 'Microsoft YaHe';-fx-font-size: 18;");
        label1.setWrapText(true);
        Label label2 = new Label("文件命名格式为：文件名+‘.'+文件类型“， 文件类型后缀不超过3个字符");
        label2.setStyle("-fx-font-family: 'Microsoft YaHe';-fx-font-size: 18;");
        label2.setWrapText(true);
        Label label3 = new Label("文件夹命名不超过3个字符，无需后缀 只需输入名字");
        label3.setStyle("-fx-font-family: 'Microsoft YaHe';-fx-font-size: 18;");
        label3.setWrapText(true);

        VBox vbox = new VBox(10);
        vbox.getChildren().addAll(label1, label2, label3);
        Scene scene = new Scene(vbox, 420, 210);
        stage2.setScene(scene);
        Image image = new Image("/resource/Image/help.png");
        stage2.getIcons().add(image);
        stage2.show();
    }

    public void setCurItem(TreeItem<ItemData> curItem) {
        this.curItem = curItem;
    }

    public ItemData getCurData() {
        if(curItem == null)
            return null;
        return curItem.getValue();
    }

    @FXML
    private TreeView<ItemData> dirTree;

    /**
     * 初始化目录树
     */
    private void initTree() {
        dirTree.setCellFactory(param -> new DirTreeCell());
        dirTree.setOnMouseClicked(event -> {
            curItem = dirTree.getSelectionModel().getSelectedItem();
            update_List();
        });

        TreeItem<ItemData> rootItem = new TreeItem<>(new ItemData());
        dirTree.setRoot(rootItem);
        curItem = dirTree.getRoot();
        recreateTree();
    }


    /**
     * 重构目录树或指定子树
     */
    public void recreateTree() {
        dirTree.getRoot().getChildren().clear();
        ManagerAppTools.addChildren(dirTree.getRoot());
        dirTree.getRoot().setExpanded(true);
    }
    public void recreateTree(TreeItem<ItemData> item) {
        item.getChildren().clear();
        ManagerAppTools.addChildren(item);
        item.setExpanded(true);
    }


    /**********
     * 文件列表 *
     **********/
    @FXML
    private TextField pathText;

    @FXML
    private ListView<ItemData> fileList;


    /**
     * 初始化文件列表
     */
    private void initList() {
        fileList.setCellFactory(param -> new FileListCell());

        /* 默认右键菜单 */
        MenuItem createFile = new MenuItem("创建文件");
        MenuItem createDir = new MenuItem("创建文件夹");
        createFile.setOnAction(event -> {
            createFileAction();
        });
        createDir.setOnAction(event -> {
            createDirAction();
        });
        fileList.setContextMenu(new ContextMenu(createFile, createDir));
    }

    /**
     * 显示已达上限
     */
    public void showLimitText() {
        new Thread(() -> {
            Platform.runLater(() -> limitPane.setVisible(true));
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Platform.runLater(() -> limitPane.setVisible(false));
        }).start();
    }


    /**********
     * 底部按钮 *
     **********/

    @FXML
    private Button crippleButton;

    @FXML
    private Button fixButton;

//    @FXML
//    private Button about;

    @FXML
    private Button formatButton;

    @FXML
    void crippleAction(ActionEvent event) {
        Manager.getInstance().crippleBlock();
        update_List();
        GUI.managerController.update_Grid();
    }

    @FXML
    void fixAction(ActionEvent event) {
        Manager.getInstance().fixDisk();
        update_List();
        GUI.managerController.update_Grid();
    }
//    @FXML
//    public void aboutAction(ActionEvent event) {
//        System.out.println("a");
//    }

    /**********
     * 右键菜单 *
     **********/
    public void openAction() {
        ItemData data = fileList.getSelectionModel().getSelectedItem();
        if(data == null)
            return;

        if(data.getEntry().isDirectory()) //打开目录
            ManagerAppTools.searchItem(dirTree.getRoot(), data);
        else //打开文件
            ManagerAppTools.openFile(curItem, data);
    }

    public void deleteAction() {
        ItemData data = fileList.getSelectionModel().getSelectedItem();
        if(data == null)
            return;
        if(data.isDirectory())
            ManagerAppTools.deleteDir(curItem, data.getPos());
        else
            ManagerAppTools.deleteFile(curItem, data.getPos());
    }

    public void changeAction() {
        GUI.createControl(curItem, fileList.getSelectionModel().getSelectedItem(), 3);
    }

    public void createFileAction() {
        GUI.createControl(curItem, null, 1);
    }

    public void createDirAction() {
        GUI.createControl(curItem, null, 2);
    }

    public void attributeAction()  {
        GUI.createAttribute(pathText.getText(), fileList.getSelectionModel().getSelectedItem());
    }


    /**
     * 更新界面
     */
    public void update_List() {
        if(curItem == null)
            return;

        /* 更新路径 */
        String path = ManagerAppTools.getPath(curItem);
        pathText.setText(path);
        /* 更新文件列表 */
        ManagerAppTools.fillList(fileList, curItem.getValue().getEntry());
        ManagerAppTools.sortList(fileList);

        dirTree.getSelectionModel().select(curItem);
    }

    @FXML
    private Text usedText;

    @FXML
    private Text idleText;

    @FXML
    private Text downText;

    @FXML
    private GridPane blockGrid;

    @FXML
    private GridPane FATIndexGrid;

    @FXML
    private GridPane FATContGrid;

//    private Label getLabelFromGridPane(GridPane gridPane, int i) {
//        for (var child : gridPane.getChildren()) {
//            if (GridPane.getColumnIndex(child) == col && GridPane.getRowIndex(child) == row && child instanceof Label) {
//                return (Label) child;
//            }
//        }
//        return null;
//    }
    StringBuilder path ;
    public  StringBuilder getPath()
    {
        return  this.path;
    }
    public void getFATConGridIndex(int index)
    {
        path= new StringBuilder();
        //StringBuilder path = new StringBuilder();
        // 循环遍历GridPane中的每个节点
        for (int i = index; i < FATContGrid.getChildren().size(); i++) {
            StackPane stackPane = (StackPane) FATContGrid.getChildren().get(i);
            StackPane stackPane1 = (StackPane) FATContGrid.getChildren().get(i+1);
            Label label = (Label) stackPane.getChildren().get(0);
            Label label1 = (Label) stackPane1.getChildren().get(0);
           // Label label = (Label) FATContGrid.getChildren().get(i);
            // 检查节点值是否为-1，如果是，则表示读取结束
            if (label.getText().equals("-1")) {

                path.append(i);
                break;
            } else if(label != null && !label.getText().isEmpty() && !label.getText().equals("-1")) {
                // 遇到值为-1，读取结束
                //int value = Integer.parseInt(label.getText())-1;
                int value = Integer.parseInt(label.getText())-1;
                path.append(value).append(" -> ");
               //if(!label1.getText().equals("-1")) path.append(" -> ");

            }
        }
        System.out.println("路径: " + path.toString());
    }
     private PieChart.Data data1 ;
     private PieChart.Data data2;
     private PieChart.Data data3;
    public void update_Grid() {
        int used = 0, idle = 0, down = 0;
        for(int i = 0; i < Manager.DISK_BLOCK; i++) {
            Node cell = blockGrid.getChildren().get(i);
            switch (Manager.FAT[i]) {
                case 0: cell.setStyle("-fx-background-color: #adadad;" +
                        "-fx-border-color: #696969"); idle++; break;
                case -2: cell.setStyle("-fx-background-color: #FF4500;" +
                        "-fx-border-color: #696969"); down++; break;
                default: cell.setStyle("-fx-background-color: #00FF7F;" +
                        "-fx-border-color: #696969"); used++;
            }
            ((Label)((StackPane) FATContGrid.getChildren().get(i)).getChildren().get(0)).setText(String.valueOf(Manager.FAT[i]));
        }
         data1 = new PieChart.Data("已经使用的容量"+String.format("%.2f",used/128.0*100)+"%",used);
         data2 = new PieChart.Data("未使用的容量"+String.format("%.2f",idle/128.0*100)+"%",idle);
         data3 = new PieChart.Data("不可使用的容量"+String.format("%.2f",down/128.0*100)+"%",down);
        ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(data1,data2,data3);

        pieChart.setData(pieChartData);
        usedText.setText("使用: " + used);
        idleText.setText("空闲: " + idle);
        downText.setText("损坏: " + down);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        /* 初始化目录树 */
//        Manager.getInstance().createDisk();
        initTree();

        /* 初始化文件列表 */
        initList();
       // pieChart = new PieChart();

        /* 初始化路径框 */
        pathText.setText("我的电脑/");

        update_List();

        for(int i = 0; i < Manager.DISK_BLOCK; i++) {
            int col = i % 8;
            int row = i / 8;
            blockGrid.add(new StackPane(new Label(String.valueOf(i))) , col, row);
            FATIndexGrid.add(new StackPane(new Label(String.valueOf(i))) , col, row);
            FATContGrid.add(new StackPane(new Label(String.valueOf(Manager.FAT[i]))) , col, row);
            FATContGrid.getChildren().get(i).setStyle("-fx-border-color: #696969");
        }
        update_Grid();
    }

}
